package com.dwxt.parabolic.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.parabolic.base.EventCode;
import com.dwxt.parabolic.entity.Company;
import com.dwxt.parabolic.entity.Device;
import com.dwxt.parabolic.entity.Event;
import com.dwxt.parabolic.entity.InstallCompany;
import com.dwxt.parabolic.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class IndexService {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private EventService eventService;

    @Autowired
    private InstallCompanyService installCompanyService;

    public BaseResult graph() {
        String installCompanyId = RequestUtil.getCurrentCompanyId();
        Map map = new HashMap();
        List<InstallCompany> installCompanyList = installCompanyService.selectById(installCompanyId);
        map.put("installCompanyCount", installCompanyList.size());
        List<Company> companyList = companyService.selectByInstallCompanyId(installCompanyId);
        map.put("companyCount", companyList.size());
        List<Device> deviceList = companyList.size() == 0 ? new ArrayList<>() :
                deviceService.selectByCompanyIdList(companyList.stream().map(Company::getId).collect(Collectors.toList()));
        map.put("deviceCount", deviceList.size());
        map.put("notOnLineCount", deviceList.size() == 0 ? 0 :
                deviceList.stream().filter(device -> device.getIsOnline() == YesOrNo.NO).count());
        map.put("cameraCount", deviceList.size() == 0 ? 0 : deviceList.stream().mapToInt(Device::getCameraCount).sum());

        List<Event> eventList = eventService.selectByInstallCompanyId(installCompanyId);
        map.put("eventCount", eventList.size());
        map.put("parabolicCount", eventList.size() == 0 ? 0 :
                eventList.stream().filter(event -> EventCode.PARABOLIC.getCode().equals(event.getEventCode())).count());
        map.put("fault", eventList.size() == 0 ? 0 :
                eventList.stream().filter(event -> EventCode.CAMERA_ERROR.getCode().equals(event.getEventCode())).count());

        map.put("installCompany", installCompanyList);
        map.put("company", companyList);
        return BaseResult.ok(map);
    }
}
